#include "utils.h"

bool is_file_exist(const char* file_name) {
  std::ifstream in_file(file_name);
  return in_file.good();
}

bool read_file(std::vector<std::string>& output, char delimiter, const char* file_name) {
  std::string line;
  std::ifstream in_file(file_name);
  if (!in_file.is_open()) {
    std::cout << "[WARN] unable to open file " << file_name << '\n';
    return false;
  }

  while (std::getline(in_file, line, delimiter)) {
    // output.emplace_back(line);
    // std::cout << "[INFO] specify IP & Port: " << line << '\n';
    std::istringstream iss(line);
    for (std::string s; iss >> s;) {
      output.emplace_back(s);
    }
  }
  in_file.close();
  return true;
}

std::unordered_map<std::string, std::string> parse_args(const std::size_t& argc, char* argv[]) {
  std::unordered_map<std::string, std::string> args;
  bool has_filename = false;
  bool has_ip = false;
  bool has_port = false;

  for (int i = 0; i < argc; ++i) {
    std::string arg = argv[i];
    if (arg.find("--filename=")==0) {
      args["filename"] = arg.substr(11);
      has_filename = true;
    }
    if (arg.find("-f=")==0) {
      args["filename"] = arg.substr(3);
      has_filename = true;
    }
    if (arg.find("--ip=")==0 or arg.find("--IP=")==0) {
      args["ip"] = arg.substr(5);
      has_ip = true;
    }
    if (arg.find("--port=")==0 or arg.find("--PORT=")==0) {
      args["port"] = arg.substr(7);
      has_port = true;
    }
  }

  if (!has_filename && !(has_ip && has_port)) {
    std::cout << "[ERROR] args not valid, specify a filename or (IP and PORT)" << '\n';
  }
  
  return args;
}